// pages/Details/main/index.js
const app = getApp()
const utils = require('./../../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIphoneX: app.globalData.isIphoneX,
    showPrivacyPopup:false,
    capBarMoveFlag:false,
    boundButtonRect:{},
    //页面数据
    detailed:{},
    id:'',
    labelBtn:[],
    userInfo:'',
    autoplay:true,
    currents:[],
    love:[],
    footerBtn:true,
    summTitle:true,
    //是否收藏
    isCollect:true,
    //是否点赞
    isLike:true,
    textItem:{
      auto:false,
      isMore:false
    },
    textItem1:{
      auto:false,
      isMore:false
    },
    clickShareFlag: false // 点击分享好友按钮标识
  },
  //
  look(e){
    let item = e.currentTarget.dataset.item
    // console.log(item)
  },
  //
  change(e){
    let current = e.detail.current
    let index = e.target.dataset.index
    let temp = `currents[${index}].num`
    this.setData({
      [temp]:current 
    })
  },
  // 查看设计详情
  setbool(e){
    // console.log(e)
    let index = e.currentTarget.dataset.index
    let temp = `currents[${index}].bool`
    let bool = this.data.currents[index].bool
    this.setData({
      [temp]:!bool
    })
  },
  // 异步获取所有数据
 async getViews() {
    await this.Getdetailed()
    this.GetProgramDataToList()
    this.GetdetailedisCollect()
    this.GetdetailedisLike()

    // 增加浏览量
    const { id } = this.data
    const openId = wx.getStorageSync('openId')
    utils.$http(app.globalData.api.getViews, { id,openId }, 'GET', true, 'JSON')
  },
  // 详情数据
  Getdetailed(){
    const id = this.data.id
    const openId = wx.getStorageSync('openId')
    return new Promise((resolve, reject) => {
      utils.$http(app.globalData.api.Getdetailed, {
        id,
        openId
      }, 'GET', true, 'JSON').then(res=> {
        if(res.data) {
          const { id : returnId } = res.data
          // 区分分享者及被分享者，被分享者则重新更新id
          if(this.data.id != returnId) {
            this.setData({ id: returnId })
          }

          let detailed = res.data
          let labelBtn = []
          let currents = []
          let footerBtn = true
          let programmeTypeCode = detailed.programmeTypeCode
          let newRoomDataList = JSON.parse(JSON.stringify(detailed.newRoomDataList))
          if(programmeTypeCode==='Ordinary' || programmeTypeCode==='Building'){
            footerBtn = false
          } else {
            footerBtn = true
          }
          if(res.data.programmeTypeCode==="Product"){
            let {cabinetColorNames = [], doorColorName = [], doorTechnologys = [],singleSpaceArea} = detailed.newRoomDataList.length && detailed.newRoomDataList[0]
            detailed['cabinetColorNames'] = cabinetColorNames
            detailed['doorColorName'] = doorColorName
            detailed['doorTechnologys'] = doorTechnologys
            detailed['houseArea'] = singleSpaceArea
          }
          for(let i = 0;i<newRoomDataList.length;i++){
            currents.push({
              num:0,
              bool:false
            })
          }
          for(let key in detailed) {
            let flag = false
            if(detailed.programmeTypeCode === 'Ordinary' || detailed.programmeTypeCode === 'Building') {
              flag = ( (key ==="cabinetColorNames" && detailed['cabinetColorNames'].length>0) ||(key ==="doorColorName" && detailed['doorColorName'].length>0) ||(key ==="doorTechnologys" && detailed['doorTechnologys'].length>0) ||(key ==="livingRoom" && detailed['livingRoom'].length>0) || (key ==="building" && detailed['building'].length>0) ||  (key ==="topics" && detailed['topics'].length>0))
            } else {
              flag = ( (key ==="cabinetColorNames" && detailed['cabinetColorNames'].length>0) ||(key ==="doorColorName" && detailed['doorColorName'].length>0) ||(key ==="doorTechnologys" && detailed['doorTechnologys'].length>0) ||(key ==="livingRoom" && detailed['livingRoom'].length>0) || (key ==="building" && detailed['building'].length>0) ||  (key ==="series" && detailed['series'].length>0)|| (key ==="topics" && detailed['topics'].length>0))
            }

            if(flag) {
              if(key === 'topics') {
                detailed.topics.forEach(item => {
                  labelBtn.push(item)
                })
              } else {
                labelBtn.push(detailed[key])
              }
            }
          }
          this.setData({
            detailed,
            labelBtn,
            currents,
            footerBtn
          })

          wx.nextTick(()=>{
            this.handlerCustomerRequreText()
          })
        } else if(res.code == 1000){
          wx.showToast({ title: res.msg, icon: 'none' });
        }
        resolve()
      }).catch((err) => {
        console.error(err)
        reject(err)
      })
    })
  },
  handlerCustomerRequreText() {
    const customerNeeds = this.data.detailed.customerNeeds ? this.data.detailed.customerNeeds : '顾客想要合理利用家的每一寸空间，根据其生活方式进行空间规划，打造一个舒适温馨的家居氛围。'
    if(customerNeeds){
     let qurey = wx.createSelectorQuery()
     qurey.select('#text-box').fields({
       size:true
     }).exec((res)=>{
        // console.log('文本展示的高度:',res)
        let lineHeight = 22
        if (res[0] && (res[0].height / lineHeight) > 2) {
           this.data.textItem.auto = true;
           this.data.textItem.isMore = true;
        }else{
            
        }
        this.setData({
          textItem:this.data.textItem
        })
     })
    }
  
    const designExplain = this.data.detailed.designExplain ? this.data.detailed.designExplain : '空间每一个细节都精心打磨，每一个元素都精准拿捏；以独特的巧思和灵活的设计，营造出一种高级的舒适感，家的静逸与幸福感足以驱走一天的疲惫。'
    if(designExplain){
     let qurey1 = wx.createSelectorQuery()
     qurey1.select('#text-box1').fields({
       size:true
     }).exec((res)=>{
        // console.log('文本展示的高度1:',res)
        let lineHeight = 22
        if (res[0] && (res[0].height / lineHeight) > 2) {
           this.data.textItem1.auto = true;
           this.data.textItem1.isMore = true;
        }else{
        }
        this.setData({
          textItem1:this.data.textItem1
        })
     })
    }
 },
   //展开更多
   toggleHandler: function (e) {
    let type = e.currentTarget.dataset.type
    if(type == 1){
      this.data.textItem.auto = true
      this.data.textItem.isMore = false
      this.setData({
         textItem:this.data.textItem
      })
    }
    if(type == 2){
      this.data.textItem1.auto = true
      this.data.textItem1.isMore = false
      this.setData({
         textItem1:this.data.textItem1
      })
    }
   
  },

   //收起更多
  toggleContent: function (e) {
    let type = e.currentTarget.dataset.type
    if(type == 1){
      this.data.textItem.auto = false
      this.data.textItem.isMore = true
      this.setData({
          textItem:this.data.textItem
       })
    }
    if(type == 2){
      this.data.textItem1.auto = false
      this.data.textItem1.isMore = true
      this.setData({
          textItem1:this.data.textItem1
       })
    }
  },
  GetProgramDataToList(){
    let id = this.data.id
    utils.$http(app.globalData.api.GetProgramDataToList, {
      id
    }, 'GET', true, 'JSON').then(res=>{
      if(res.data){
        let love = res.data
        this.setData({
          love
        })
      }
    })
  },
  //
  ExpandDetails(){
    this.setData({
      summTitle: !this.data.summTitle
    })
  },
  //
  toLoginPage() {
    let message = ''
    if(!this.data.userInfo) {
      message = '未登陆，是否跳到登陆页登陆'
    }
    wx.showModal({
      title: '提示',
      content: message,
      success:function(res) {
        if(res.confirm){
          wx.navigateTo({
            url: '/pages/mine/register/index'
          });
        }
      }
    })
  },
  // 0元设计
  gotofree() {
    wx.navigateTo({
      url: '/pages/design/index/index',
    })
  },
  //收藏
  Favorites(){
    let id = this.data.id 
    let isCollect = this.data.isCollect
    const arr=[]
    arr.push(id)
    let openId = wx.getStorageSync('openId')
    if(!isCollect){
      utils.$http(app.globalData.api.GetdetailedaddCollect, {
        programmeId:id,
        // programmeIds:arr,
        openId
      }, 'POST', true, 'JSON').then(res=>{
        if(res.success===1){
          this.GetdetailedisCollect()
        }
        // this.Getdetailed()
      })
    }else{
      utils.$http(app.globalData.api.GetdetailedcancelCollect, {
        programmeIds:arr,
        openId
      }, 'POST', true, 'JSON').then(res=>{
        if(res.success===1){
          this.GetdetailedisCollect()
        }
        // this.Getdetailed()
      })
    }
    
  },
  //点赞
  DianZan(){
    let id = this.data.id 
    let isLike = this.data.isLike
    let openId = wx.getStorageSync('openId')
    if(!isLike){
      utils.$http(app.globalData.api.GetdetailedaddLike, {
        programmeId:id,
        openId
      }, 'POST', true, 'JSON').then(res=>{
        if(res.success===1){
          this.GetdetailedisLike()
        }
      })
    }else{
      utils.$http(app.globalData.api.Getdetailedcancellike, {
        programmeId:id,
        openId
      }, 'POST', true, 'JSON').then(res=>{
        if(res.success===1){
          this.GetdetailedisLike()
        }
      })
    }
    this.Getdetailed()
  },
  //是否收藏
  GetdetailedisCollect(){
    let id = this.data.id 
    const arr=[]
    arr.push(id)
    let openId = wx.getStorageSync('openId')
    utils.$http(app.globalData.api.GetdetailedisCollect, {
      programmeIds:arr,
      openId
    }, 'POST', true, 'JSON').then(res=>{
      if(res.success===1){
        let isCollect = res.data
        this.setData({
          isCollect
        })
      }
    })
  },
  //是否点赞
  GetdetailedisLike(){
    let id = this.data.id 
    let openId = wx.getStorageSync('openId')
    utils.$http(app.globalData.api.GetdetailedisLike, {
      programmeId:id,
      openId
    }, 'POST', true, 'JSON').then(res=>{
      if(res.success===1){
        let isLike = res.data
        this.setData({
          isLike
        })
      }
    })
  },
  //跳转全屋
  gotopanoramaUrl(e){
    let url = e.currentTarget.dataset.url
    // console.log(url)
    wx.navigateTo({
      url: `/pages/H5/main/index?url=${encodeURIComponent(url)}`,
    })
  },
  //跳转到详情
  gotoDL(e){
    let id = e.currentTarget.dataset.id
    // console.log(id)
    wx.navigateTo({
      url: `/pages/Details/main/index?id=${id}`,
    })
  },
  getBoundButtonRect:function(){
    let data = wx.getMenuButtonBoundingClientRect()
    const screenWidth =  app.globalData.screenWidth 
    const { right = 0, top, height, width} = data 
    let left = screenWidth - right

    this.setData(
      {
         boundButtonRect: {
           left,
           height,
           top,
           width
         }
      }
    )
  },

  goBack:function(){
    const currentPages = getCurrentPages()
    if (currentPages.length <= 1){
       wx.switchTab({
         url: '/pages/home/main/index',
       })
    }  else {
      wx.navigateBack({
        // delta: 1,
        // success: function (e) {
        //   const page = getCurrentPages().pop();
        //   if (page == undefined || page == null) return;
        //   page.onLoad();
        //  }
      })
    }
  
  },

  goHome:function(){
    wx.switchTab({
      url: '/pages/home/main/index'
    })
  },
  /**
   * 获取本地用户信息
  */
  getLocalUserInfo: function(){
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo){
      this.setData({ userInfo, phone: userInfo.phone })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options)
    this.getBoundButtonRect()
    this.getLocalUserInfo()
    const userInfo = wx.getStorageSync("userInfo")
    if(userInfo){
      this.setData({showPrivacyPopup:true})
    }

    const {  id , scene, sharerPhone } = options
    if(scene) {// 二维码分享进来
      this.setData({ id: scene })
      this.GetQRCodeInformation(scene)
    } else {
      this.setData({ id })
      if(sharerPhone) wx.setStorageSync('sharerPhone', sharerPhone) // 通过微信自带的获取进来 获取分享人信息
    }

    this.getViews()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  onPageScroll(e){
    const isSatisfy = e.scrollTop  >= 100  // 高度大于100的时候 显示白底标签栏
    if(this.data.capBarMoveFlag == isSatisfy) { 
      return false;
    } else {
      this.setData({
        capBarMoveFlag: isSatisfy
      })
    }
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  // 获取分享人的电话号码
  GetQRCodeInformation(scene) {
    const openId = wx.getStorageSync('openId') 

    utils.$http(app.globalData.api.GetQRCodeInformation, {
      code: scene,
      openId: openId
    }, 'GET', true, 'JSON').then(res=> {
      if(res.success === 1 && res.data) {
        const { phone = '' } = res.data
        wx.setStorageSync('sharerPhone', phone)
      }
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    const sharerPhone = wx.getStorageSync('phone') || ''
    const sharerOpenId = wx.getStorageSync('openId') 
    
    const imageUrl = this.data.detailed.coverSecondaryImageUrl ? utils.filterURL(this.data.detailed.coverSecondaryImageUrl) : utils.filterURL(this.data.detailed.coverImageUrl)

    return {
      title: this.data.detailed.programmeName || '详情页',
      imageUrl: imageUrl,
      path: "pages/Details/main/index?id=" + this.data.detailed.id + "&sharerPhone=" + sharerPhone + "&sharerOpenId=" + sharerOpenId
    }
  },
  getShare() {
    const sharerPhone = wx.getStorageSync('phone') || ''
    const userInfo =  wx.getStorageSync("userInfo")
    
    const params = {
      width: '400',
      page: 'pages/Details/main/index', // 分享进入小程序的页面
      userName: userInfo == null ? '' : userInfo.unionId,
      userPhone: userInfo == null ? '' : userInfo.phone ? userInfo.phone : sharerPhone,
      userHead: userInfo == null ? '' : userInfo.headImg,
      userID: userInfo == null ? '' : userInfo.userName,
      dsgnId: this.data.detailed.id,
      objType: 0,
      sharingParty: 'ads'
    }
    return  utils.$http(app.globalData.api.addShareRecord, params, 'POST', true, 'JSON')
  },
  // 分享好友
 async handleShare() {
  //  console.log('handleShare')
   this.setData({
     clickShareFlag: true
   })
    const res = await this.getShare()
    const code = res && res.data // 用于分享卡片找对应的方案id 用于记录分享数量
   
    const imageURl = this.data.detailed.coverSecondaryImageUrl ? utils.filterURL(this.data.detailed.coverSecondaryImageUrl) : utils.filterURL(this.data.detailed.coverImageUrl)
    const url = '/pages/share/index?id=' + this.data.detailed.id + '&code=' + code + '&shareName=' + this.data.detailed.programmeName + '&url=' + imageURl + "&source=ads" 
    const that = this
    wx.navigateTo({
       url: url,
       complete: function(e) {
        that.setData({
          clickShareFlag: false
        })
       }
     })
  },
  // 图片预览
  previewImage(e) {
    const { url , urls } = e.currentTarget.dataset
    let newUrls = []
    if(Array.isArray(urls)) {
      newUrls = urls.map(v => { return v.smallImageUrl ? utils.filterURL(v.smallImageUrl) : utils.filterURL(v.imageUrl) })
    } else {
      newUrls = [url]
    }
    wx.previewImage({ 
      urls: newUrls,
      current: url,
      showmenu: false,
    })
  }
})